package com.yonyou.service;

import com.yonyou.exception.ErrorMessageException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author: wangchu
 * @date: 2025-06-29 16:02
 * @description:
 */
@Slf4j
@Service
public class MailService {

    @Value("${spring.mail.username}")
    private String userName;
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送简单邮件
     * @param targetMailAddress 目标邮箱地址
     * @param title 邮件标题
     * @param content 邮件内容
     */
    public void simpleMessage(String targetMailAddress, String title, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(targetMailAddress);
        message.setText(content);
        message.setSubject(title);
        message.setFrom(userName);
        mailSender.send(message);
    }

    /**
     * 发送富文本邮件
     * @param targetMailAddress 目标邮箱地址
     * @param title 邮件标题
     * @param content 邮件内容
     */
    public void htmlMessage(String targetMailAddress, String title, String content) {
        try{
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(targetMailAddress);
            helper.setText(content, true);
            helper.setSubject(title);
            helper.setFrom(userName);
            mailSender.send(message);
        }catch (Exception ex){
            log.error("富文本邮件发送异常！", ex);
            throw new ErrorMessageException("富文本邮件发送异常！" + ex.getMessage());
        }
    }

    /**
     * 发送带附件的邮件
     * @param targetMailAddress 目标邮箱地址
     * @param title 邮件标题
     * @param content 邮件内容
     * @param attachments 附件列表
     */
    public void attachmentMail(String targetMailAddress, String title, String content, MultipartFile[] attachments) {
        try{
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(targetMailAddress);
            helper.setText(content, true);
            helper.setSubject(title);
            helper.setFrom(userName);
            for(MultipartFile attachment: attachments){
                FileSystemResource file = new FileSystemResource(multipartFileToFile(attachment));
                String fileName = file.getFilename();
                helper.addAttachment(fileName, file);
            }
            mailSender.send(message);
        }catch (Exception ex){
            log.error("附件邮件发送异常！", ex);
            throw new ErrorMessageException("附件邮件发送异常！" + ex.getMessage());
        }
    }

    /**
     * MultipartFile转File
     */
    private File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile;
        if (file.equals("") || file.getSize() <= 0) {
            toFile = null;
        } else {
            InputStream ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    private void inputStreamToFile(InputStream ins, File file) throws Exception {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    }
}